import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const api = axios.create({
  baseURL: '/api/v1',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 添加认证token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    return config
  },
  (error) => {
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response
  },
  async (error) => {
    const { response } = error
    
    if (response) {
      const { status, data } = response
      
      // 处理不同的HTTP状态码
      switch (status) {
        case 401:
          // 未认证，尝试刷新token
          if (data.message?.includes('已过期') && localStorage.getItem('refreshToken')) {
            try {
              const refreshToken = localStorage.getItem('refreshToken')
              const refreshResponse = await axios.post('/api/v1/auth/refresh', {
                refreshToken
              })
              
              if (refreshResponse.data.success) {
                const { tokens } = refreshResponse.data.data
                localStorage.setItem('token', tokens.accessToken)
                localStorage.setItem('refreshToken', tokens.refreshToken)
                
                // 重试原请求
                const originalRequest = error.config
                originalRequest.headers.Authorization = `Bearer ${tokens.accessToken}`
                return api.request(originalRequest)
              }
            } catch (refreshError) {
              console.error('刷新令牌失败:', refreshError)
            }
          }
          
          // 清除本地认证信息并跳转到登录页
          localStorage.removeItem('token')
          localStorage.removeItem('refreshToken')
          if (window.location.pathname !== '/login') {
            window.location.href = '/login'
          }
          break
          
        case 403:
          ElMessage.error(data.message || '权限不足')
          break
          
        case 404:
          ElMessage.error('请求的资源不存在')
          break
          
        case 422:
          // 验证错误
          if (data.error?.validationErrors) {
            const errors = data.error.validationErrors
            const errorMsg = errors.map(err => err.message).join(', ')
            ElMessage.error(errorMsg)
          } else {
            ElMessage.error(data.message || '请求参数错误')
          }
          break
          
        case 429:
          ElMessage.error('请求过于频繁，请稍后再试')
          break
          
        case 500:
          ElMessage.error('服务器内部错误，请稍后再试')
          break
          
        default:
          ElMessage.error(data.message || '网络错误，请检查网络连接')
      }
    } else if (error.code === 'ECONNABORTED') {
      ElMessage.error('请求超时，请检查网络连接')
    } else {
      ElMessage.error('网络错误，请检查网络连接')
    }
    
    return Promise.reject(error)
  }
)

// API方法封装
export const apiMethods = {
  // 认证相关
  auth: {
    login: (data) => api.post('/auth/login', data),
    register: (data) => api.post('/auth/register', data),
    logout: (data) => api.post('/auth/logout', data),
    getCurrentUser: () => api.get('/auth/me'),
    refreshToken: (data) => api.post('/auth/refresh', data),
    changePassword: (data) => api.put('/auth/change-password', data),
    forgotPassword: (data) => api.post('/auth/forgot-password', data),
    resetPassword: (data) => api.post('/auth/reset-password', data)
  },
  
  // 用户相关
  users: {
    getList: (params) => api.get('/users', { params }),
    getById: (id) => api.get(`/users/${id}`),
    update: (id, data) => api.put(`/users/${id}`, data),
    updateStatus: (id, data) => api.put(`/users/${id}/status`, data),
    updateRole: (id, data) => api.put(`/users/${id}/role`, data),
    delete: (id) => api.delete(`/users/${id}`),
    getStats: () => api.get('/users/stats'),
    resetPassword: (id, data) => api.put(`/users/${id}/reset-password`, data)
  },
  
  // 茶叶批次相关
  batches: {
    create: (data) => api.post('/batches', data),
    getList: (params) => api.get('/batches', { params }),
    getById: (id) => api.get(`/batches/${id}`),
    getByBatchId: (batchId) => api.get(`/batches/public/${batchId}`),
    update: (id, data) => api.put(`/batches/${id}`, data),
    search: (params) => api.get('/batches/search', { params }),
    getStats: () => api.get('/batches/stats'),
    addProduction: (id, data) => api.post(`/batches/${id}/production`, data),
    addLogistics: (id, data) => api.post(`/batches/${id}/logistics`, data),
    addSales: (id, data) => api.post(`/batches/${id}/sales`, data),
    getPublic: (id) => api.get(`/batches/public/${id}`)
  }
}

export { api }
export default api